package com.dawnClass.controller;

import com.dawnClass.service.ConsumerService;
import com.dawnClass.util.RSAUtils;
import com.dawnClass.util.ServiceResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;

@Controller
public class ConsumerController {
    @Autowired
    private ConsumerService consumerService;



    @GetMapping("/publickey1")
    @ResponseBody
    public ServiceResponse resregister() {

        return consumerService.getPublicKey1();
    }

    @GetMapping("/encrypted1")
    @ResponseBody
    public ServiceResponse password(@RequestParam("encrypted1") String encrypted) {
        System.out.println("密文: ");
        System.out.println(encrypted);

        String privateKey = consumerService.getPrivateKey1();

        try {
            System.out.println("解密中.....");
            String decryptedBytes = RSAUtils.privateDecrypt(encrypted, RSAUtils.getPrivateKey(privateKey));
            System.out.println("解密后：" + decryptedBytes);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    @PostMapping("login")
    public ModelAndView getByConsumerNameAndConsumerPassword(Long consumerTel,String consumerPassword,HttpSession session){
        System.out.println("前端返回的密码："+consumerPassword);
        System.out.println("session id"+session.getId());
        ServiceResponse serviceResponse = consumerService.getByConsumerNameAndConsumerPassword(consumerTel,consumerPassword);

        ModelAndView mav = new ModelAndView();

        System.out.println(serviceResponse);
        if(serviceResponse.getCode() == 200){ // 用户找到了，也就是 用户名和密码是正确的，跳转到首页index.jsp , 首页中显示用户名
            session.setAttribute("ServiceResponse",serviceResponse); // 绑定登录用户 到session中
            mav.setViewName("index");   //

        }else{ //  用户名和密码是错误的，跳转到login.jsp ，提示 用户名或密码错误，请重新输入
            mav.addObject("loginMsg1","手机号码或密码错误，请重新输入");
            mav.setViewName("login/login"); //  /customer/login.jsp
        }
        return mav;
    }






    //退出
    @GetMapping("logout")
    public String logout(HttpSession session){
        session.removeAttribute("ServiceResponse");// 退出： 移除session中的登录用户
        return "redirect:/index";  // 重定向(绝对路径)
        }
        }
